package com.cn.yugan.Widget.NestedView.RecycleView;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by Rover on 2016/8/18 .
 * Email 357319517@qq.com
 */


public class EmptyRecyclerView extends RecyclerView {
    View emptyView;
    final AdapterDataObserver observer = new AdapterDataObserver() {
        public void onChanged() {
            super.onChanged();
            EmptyRecyclerView.this.checkIfEmpty();
        }
    };

    public EmptyRecyclerView(Context context) {
        super(context);
    }

    public EmptyRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EmptyRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    void checkIfEmpty() {
        if (this.emptyView != null) {
            this.emptyView.setVisibility(this.getAdapter().getItemCount() > 0 ? GONE : VISIBLE);
        }

    }

    public void swapAdapter(Adapter adapter, boolean removeAndRecycleExistingViews) {
        Adapter oldAdapter = this.getAdapter();
        if (oldAdapter != null) {
            oldAdapter.unregisterAdapterDataObserver(this.observer);
        }

        if (adapter != null) {
            adapter.registerAdapterDataObserver(this.observer);
        }

        super.swapAdapter(adapter, removeAndRecycleExistingViews);
        this.checkIfEmpty();
    }

    public void setAdapter(Adapter adapter) {
        Adapter oldAdapter = this.getAdapter();
        if (oldAdapter != null) {
            oldAdapter.unregisterAdapterDataObserver(this.observer);
        }

        super.setAdapter(adapter);
        if (adapter != null) {
            adapter.registerAdapterDataObserver(this.observer);
        }

    }

    public void setEmptyView(View emptyView) {
        this.emptyView = emptyView;
        this.checkIfEmpty();
    }
}
